package com.ruoyi.school.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.google.gson.Gson;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.school.Exception.BussnissExecption;
import com.ruoyi.school.domain.WeChatSessionModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ruoyi.school.mapper.UserMapper;
import com.ruoyi.school.domain.User;
import com.ruoyi.school.service.IUserService;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户模块Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-04-10
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService 
{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${APPID}")
    private String appid;

    @Value("${APPSECRET}")
    private String appsecret;

    public User checkLogin(String code, HttpServletRequest request) {
        // 根据传入code，调用微信服务器，获取唯一openid
        // 微信服务器接口地址
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appsecret
                + "&js_code=" + code + "&grant_type=authorization_code";
        String errmsg = "";
        String errcode = "";
        String session_key = "";
        String openid = "";
        WeChatSessionModel weChatSessionModel;
        // 发送请求
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        // 判断请求是否成功
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            // 获取主要内容
            String sessionData = responseEntity.getBody();
            Gson gson = new Gson();
            //将json字符串转化为实体类;
            weChatSessionModel = gson.fromJson(sessionData, WeChatSessionModel.class);
            log.info("返回的数据==>{}", weChatSessionModel);
            //获取用户的唯一标识openid
            openid = weChatSessionModel.getOpenid();
            //获取错误码
            errcode = weChatSessionModel.getErrcode();
            //获取错误信息
            errmsg = weChatSessionModel.getErrmsg();
            session_key = weChatSessionModel.getSession_key();

        } else {
            log.info("出现错误，错误信息：{}", errmsg);
            throw new BussnissExecption(errmsg);
        }
        // 判断是否成功获取到openid
        if ("".equals(openid) || openid == null) {
            log.info("错误获取openid,错误信息:{}", errmsg);
            throw new BussnissExecption(errmsg);
        } else {
            // 判断用户是否存在，查询数据库
           User userInfo=userMapper.getObjByOpenid(openid);
            // 不存在，加入数据表
            if (userInfo == null) {
                // 填充初始信息
                // 加入数据表
                //状态 1禁用 0正常 2审核
                User user = new User(null,"","",session_key,openid,"0");
                userMapper.insertUser(user);
                return user;
            } else {
                if (!userInfo.getStatus().equals('1')){
                    return userInfo;
                }else {
                    throw new BussnissExecption("账号被禁，请联系管理员");
                }
            }
        }
    }

    @Override
    public List<User> getGuanOrFen(Long index, Long userId) {

        return userMapper.getGuanOrFen(index,userId);
    }

    @Override
    public User selectUserById(Long id)
    {
        return userMapper.selectUserById(id);
    }

    /**
     * 查询用户模块列表
     * 
     * @param user 用户模块
     * @return 用户模块
     */
    @Override
    public List<User> selectUserList(User user)
    {
        return userMapper.selectUserList(user);
    }


}
